package com.google.project.client.Admin;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.ListBox;
import com.google.project.client.Service.UsersService;
import com.google.project.client.Service.UsersServiceAsync;
import com.google.project.shared.UsersDTO;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.Label;

public class ADMCreateAccount extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField ListBox cbUserGroup;
	@UiField TextBox txtUserCode;
	@UiField Button btnSave;
	@UiField Button btnCancel;
	@UiField PasswordTextBox txtPassword;
	@UiField TextBox txtUserName;
	@UiField Label lblTitle;
	@UiField Button btnResetPass;
	
	private UsersDTO currentUser = new UsersDTO();
	private List<UsersDTO> userList = new ArrayList<UsersDTO>();
	private final UsersServiceAsync userService = GWT.create(UsersService.class);
	
	interface Binder extends UiBinder<Widget, ADMCreateAccount> {
	}

	public ADMCreateAccount() {
		initWidget(binder.createAndBindUi(this));
	}
	
	public ADMCreateAccount(String userId) {
		this();
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	txtUserName.setFocus(true);
	        }
	    });
		initCbGroup();
		currentUser.setUserId(userId);
		getUserInfo(userId);
	}
	
	public void initCbGroup() {
		cbUserGroup.addItem("---Chọn---","0");
		cbUserGroup.addItem("Giám đốc","1");
		cbUserGroup.addItem("Quản lý","2");
		cbUserGroup.addItem("Chỉ huy công trường","3");
		cbUserGroup.addItem("Quản lý nhân sự","4");
		cbUserGroup.addItem("Nhân viên","5");
		cbUserGroup.addItem("Admin","6");
		cbUserGroup.setSelectedIndex(0);
	}
	
	private void getUserInfo(String userId) {
		userService.getUserById(userId, new AsyncCallback<UsersDTO>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Cập nhật thất bại!");
			}

			@Override
			public void onSuccess(UsersDTO result) {
				currentUser = result;
				getAllAccount();
			}
		});
	}

	//Lay toan bo Ten tai khoan cua nhung tai khoan dang hoat dong(status = 2)
	private void getAllAccount() {
		userService.getUserListByStatus("2", new AsyncCallback<List<UsersDTO>>() {
			@Override
			public void onSuccess(List<UsersDTO> result) {
				for(UsersDTO userDTO : result) {
					userList.add(userDTO);
				}
				displayAccount();
			}

			@Override
			public void onFailure(Throwable caught) {
			}
		}); 
	}
	
	protected void displayAccount() {
		if(currentUser.getUserName() != null) {
			lblTitle.setText("CẬP NHẬT TÀI KHOẢN");
			int userGroupIndex = Integer.parseInt(currentUser.getUserGroup().toString());
			cbUserGroup.setSelectedIndex(userGroupIndex);
			txtUserName.setText(currentUser.getUserName());
			txtUserName.setEnabled(false);
			txtPassword.setText(currentUser.getPassword());
		}
		txtUserCode.setText(currentUser.getUserCode());
	}
	@UiHandler("btnSave")
	void onBtnSaveClick(ClickEvent event) {
		if(validateData()) {
			currentUser.setUserName(txtUserName.getText());
			currentUser.setPassword(txtPassword.getText());
			int index = cbUserGroup.getSelectedIndex();
			currentUser.setUserGroup(Long.parseLong(cbUserGroup.getValue(index)));
			currentUser.setStatus("2");
			userService.updateAccount(currentUser, new AsyncCallback<Void>() {
				@Override
				public void onFailure(Throwable caught) {
					Window.alert("Thực hiện thất bại!");
				}
	
				@Override
				public void onSuccess(Void result) {
					Window.alert("Thực hiện thành công!");
					ADMEntrypoint.get().ADMAccountList();
				}
			});
		}
	}
	public boolean validateData() {
		String userName = txtUserName.getText().trim();
		String pass = txtPassword.getText().trim();
		String userGroup = cbUserGroup.getValue(cbUserGroup.getSelectedIndex());
		if(userName.equals("")) {
			Window.alert("Bạn phải nhập Tên tài khoản!");
			Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
		        public void execute () {
		        	txtUserName.setFocus(true);
		        }
		    });
			return false;
		}
		if(currentUser.getStatus().equals("1")) {
			for(UsersDTO userDTO : userList) {
				if(userDTO.getUserName().equals(userName)) {
					Window.alert("Tài khoản này đã có người dùng! Bạn hãy nhập Tên tài khoản khác!");
					txtUserName.setText("");
					Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
				        public void execute () {
				        	txtUserName.setFocus(true);
				        }
				    });
					return false;
				}
			}
		}
		//Validate pass: Co it nhat 6 ky tu
		if(pass.length() < 6) {
			Window.alert("Mật khẩu phải có ít nhất 6 ký tự!");
			txtPassword.setText("");
			Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
		        public void execute () {
		        	txtPassword.setFocus(true);
		        }
		    });
			return false;
		}
		//Validate Nhom tai khoan
		if(userGroup.endsWith("0")) {
			Window.alert("Bạn phải chọn Nhóm tài khoản!");
			Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
		        public void execute () {
		        	cbUserGroup.setFocus(true);
		        }
		    });
			return false;
		}
		return true;
	}
	
	@UiHandler("btnCancel")
	void onBtnCancelClick(ClickEvent event) {
		ADMEntrypoint.get().ADMAccountList();
	}
	@UiHandler("btnResetPass")
	void onBtnResetPassClick(ClickEvent event) {
//		if(currentUser.getStatus().equals("2")) {
			txtPassword.setValue("123456");	//Set Mat khau mac dinh 123456
//		}
	}
}
